package com.itwill.ecom.orders;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itwill.ecom.cart.CartBeans;
import com.itwill.ecom.cart.CartServiceImpl;
import com.itwill.ecom.member.MemberBeans;
import com.itwill.ecom.member.MemberServiceImpl;
import com.itwill.ecom.ordersDetail.OrdersDetailBeans;
import com.itwill.ecom.ordersDetail.OrdersDetailServiceImpl;
import com.itwill.ecom.product.ProductBeans;
import com.itwill.ecom.product.ProductServiceImpl;

@Controller
@RequestMapping("/orders")
public class OrdersController {
	@Autowired
	private OrdersServiceImpl ordersService;
	@Autowired
	private MemberServiceImpl memberService;
	@Autowired
	private OrdersDetailServiceImpl ordersDetailService;
	@Autowired
	private ProductServiceImpl productService;
	@Autowired
	private CartServiceImpl cartService;
	
	public OrdersController() {
	}	
	
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String create(Model model, HttpSession session) throws Exception {		
		String sid = (String)session.getAttribute("sid");
		MemberBeans member = memberService.getMemberById(sid);		
		model.addAttribute("member", member);
		
		List<CartBeans> cartList = null;
		ArrayList<ProductBeans> productList = new ArrayList<ProductBeans>();
		
		int count = 0;
		int totalPrice = 0;
		
		cartList = cartService.getCartListByMemberNo(member.getMember_no());
		for(CartBeans cart : cartList){
			ProductBeans product = productService.getProductByNo(cart.getCart_product());
			productList.add(product);
			
			count++;
			totalPrice += cart.getCart_count() * product.getProduct_price();
		}
		
		model.addAttribute("cartList", cartList);
		model.addAttribute("productList", productList);
		model.addAttribute("count", count);
		model.addAttribute("totalPrice", totalPrice);
		
		return "/orders/orders_home";	
	}

	// 주문 배송 조회(리스트)
	@RequestMapping(value = "/list")
	public String list(Model model, HttpSession session, HttpServletRequest request) {
		String sid = (String)session.getAttribute("sid");
		MemberBeans member = memberService.getMemberById(sid);
				
		HashMap<String, String> pagemap = new HashMap<String, String>();
		int pageno;
		
		try{
			pageno = Integer.parseInt(request.getParameter("pageno"));
			if(pageno < 1) pageno = 1;
		}
		catch(Exception e){
			pageno = 1;
		}
		
		int itemsPerList = 10;
		int start_no = (pageno - 1) * itemsPerList + 1;
		int end_no = pageno * itemsPerList;
		int m_no = member.getMember_no();
		
		pagemap.put("m_no", Integer.toString(m_no));
		pagemap.put("start_no", Integer.toString(start_no));
		pagemap.put("end_no", Integer.toString(end_no));
		
		List<OrdersBeans> list = ordersService.getOrdersByMemberNo(pagemap);
				
		int allCount = ordersService.getOrdersCount(m_no);
		int totalPageCount = allCount / itemsPerList;
		if(allCount % itemsPerList != 0) totalPageCount++;
		int pageListCount = 7;
		
		int startPageNo = pageno - (pageListCount / 2);
		if(startPageNo < 1) startPageNo = 1;
		
		int endPageNo = startPageNo + pageListCount - 1;
		if(endPageNo > totalPageCount) endPageNo = totalPageCount;
		
		startPageNo = endPageNo - pageListCount + 1;
		if(startPageNo < 1) startPageNo = 1;
		
		String label = "";
		
		if(pageno == 1) label += "<a style='color: black;'>[처음 페이지]   </a>";
		else label += "<a href='list?pageno=1'>[처음 페이지]   </a>";
		
		if(pageno == 1) label += "◀";
		else label += "<a href='list?pageno=" + (pageno - 1) + "'>◀</a>";
		
		label += "  ...  ";
		
		for(int i = startPageNo ; i <= endPageNo ; i++){
			if(i == pageno) label += "<a style='color: black;'> " + i + " </a>";
			else label += "<a href='list?pageno=" + i + "'> " + i + " </a>";
		}
		
		label += "  ...  ";
		
		if(pageno == totalPageCount) label += "▶";
		else label += "<a href='list?pageno=" + (pageno + 1) + "'> ▶ </a>";
		
		if(pageno == totalPageCount) label += "<a style='color: black;'>   [마지막 페이지]</a>";
		else label += "<a href='list?pageno=" + totalPageCount + "'>   [마지막 페이지]</a>";
		
		model.addAttribute("beans", list);
		model.addAttribute("label", label);
		
		return "/orders/orders_list";
	}

	// 결제 읽기
	@RequestMapping(value = "/view", method = RequestMethod.POST)
	public String view(Model model, @RequestParam(value = "o_no") int orders_no) throws Exception {
		OrdersBeans ordersBeans = ordersService.getOrdersByOrdersNo(orders_no);
		List<OrdersDetailBeans> ordersDetailBeans = ordersDetailService.getDetail(orders_no);
		ArrayList<ProductBeans> productBeansList = new ArrayList<ProductBeans>();
		for(OrdersDetailBeans temp : ordersDetailBeans){
			ProductBeans productBeans = productService.getProductByNo(temp.getOdetail_product());
			productBeansList.add(productBeans);
		}
		
		model.addAttribute("beans", ordersBeans);
		model.addAttribute("details", ordersDetailBeans);
		model.addAttribute("product", productBeansList);
		model.addAttribute("stat", false);
		
		return "/orders/orders_view";
	}
	
	// 결제완료
	@RequestMapping(value = "/order_complete", method = RequestMethod.POST)
	public String complete(Model model, HttpSession session,
			@RequestParam(value = "r_name") String r_name,
			@RequestParam(value = "r_mail") String r_mail,
			@RequestParam(value = "r_tel1") String r_tel1,
			@RequestParam(value = "r_tel2") String r_tel2,
			@RequestParam(value = "r_tel3") String r_tel3,
			@RequestParam(value = "zipcode1") String r_zip1,
			@RequestParam(value = "zipcode2") String r_zip2,
			@RequestParam(value = "addr1") String r_addr1,
			@RequestParam(value = "r_addr2") String r_addr2,
			@RequestParam(value = "r_memo") String r_memo,
			@RequestParam(value = "price") String price,
			@RequestParam(value = "payments") String payments
			) throws Exception {
		String sid = (String)session.getAttribute("sid");
		MemberBeans member = memberService.getMemberById(sid);
		
		// ordersDB에 입력
		OrdersBeans order = new OrdersBeans(0, member.getMember_no(), null, r_name, r_mail, r_tel1 + "-" + r_tel2 + "-" + r_tel3, 
											r_zip1 + "-" + r_zip2, r_addr1, r_addr2, price, payments, r_memo);
		ordersService.createOrders(order);
		
		// ordersDetailDB에 입력
		int order_no = ordersService.getMaxOrdersNo(member.getMember_no());
		List<CartBeans> cartList = cartService.getCartListByMemberNo(member.getMember_no());
		ArrayList<OrdersDetailBeans> orderDetailList = new ArrayList<OrdersDetailBeans>();
		ArrayList<ProductBeans> productList = new ArrayList<ProductBeans>();
		for(CartBeans cart : cartList){
			ProductBeans product = productService.getProductByNo(cart.getCart_product());
			productList.add(product);
			OrdersDetailBeans ordersDetail = new OrdersDetailBeans(0, order_no, product.getProduct_no(), cart.getCart_count());
			orderDetailList.add(ordersDetail);
			ordersDetailService.createOrdersDetail(ordersDetail);
		}
		
		// cartDB 삭제
		cartService.deleteCartListByMemberNo(member.getMember_no());
		
		order = ordersService.getOrdersByOrdersNo(order_no);
		
		model.addAttribute("o_no", order_no);
		model.addAttribute("beans", order);
		model.addAttribute("details", orderDetailList);
		model.addAttribute("product", productList);
		model.addAttribute("stat", true);
		
		System.out.println("싸이즈1 : " + orderDetailList.size());
		System.out.println("싸이즈2 : " + productList.size());
		return "/orders/orders_view";
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public String deleteOrders(@RequestParam(value = "o_no") int o_no, 
							HttpSession session,
							Model model,
							HttpServletRequest request) throws Exception{
		
		ordersDetailService.deleteByOno(o_no);
		ordersService.deleteOrders(o_no);
		
		session.setAttribute("sid", "master");
		String sid = (String)session.getAttribute("sid");
		MemberBeans member = memberService.getMemberById(sid);
				
		HashMap<String, String> pagemap = new HashMap<String, String>();
		int pageno;
		
		try{
			pageno = Integer.parseInt(request.getParameter("pageno"));
			if(pageno < 1) pageno = 1;
		}
		catch(Exception e){
			pageno = 1;
		}
		
		int itemsPerList = 10;
		int start_no = (pageno - 1) * itemsPerList + 1;
		int end_no = pageno * itemsPerList;
		int m_no = member.getMember_no();
		
		pagemap.put("m_no", Integer.toString(m_no));
		pagemap.put("start_no", Integer.toString(start_no));
		pagemap.put("end_no", Integer.toString(end_no));
		
		List<OrdersBeans> list = ordersService.getOrdersByMemberNo(pagemap);
				
		int allCount = ordersService.getOrdersCount(m_no);
		int totalPageCount = allCount / itemsPerList;
		if(allCount % itemsPerList != 0) totalPageCount++;
		int pageListCount = 7;
		
		int startPageNo = pageno - (pageListCount / 2);
		if(startPageNo < 1) startPageNo = 1;
		
		int endPageNo = startPageNo + pageListCount - 1;
		if(endPageNo > totalPageCount) endPageNo = totalPageCount;
		
		startPageNo = endPageNo - pageListCount + 1;
		if(startPageNo < 1) startPageNo = 1;
		
		String label = "";
		
		if(pageno == 1) label += "<a style='color: black;'>[처음 페이지]   </a>";
		else label += "<a href='list?pageno=1'>[처음 페이지]   </a>";
		
		if(pageno == 1) label += "◀";
		else label += "<a href='list?pageno=" + (pageno - 1) + "'>◀</a>";
		
		label += "  ...  ";
		
		for(int i = startPageNo ; i <= endPageNo ; i++){
			if(i == pageno) label += "<a style='color: black;'> " + i + " </a>";
			else label += "<a href='list?pageno=" + i + "'> " + i + " </a>";
		}
		
		label += "  ...  ";
		
		if(pageno == totalPageCount) label += "▶";
		else label += "<a href='list?pageno=" + (pageno + 1) + "'> ▶ </a>";
		
		if(pageno == totalPageCount) label += "<a style='color: black;'>   [마지막 페이지]</a>";
		else label += "<a href='list?pageno=" + totalPageCount + "'>   [마지막 페이지]</a>";
		
		model.addAttribute("beans", list);
		model.addAttribute("label", label);
		return "/orders/orders_list";
	}
	
	
	
	// JSON 요청
	@RequestMapping("/getCartList")
	public @ResponseBody ArrayList<ProductBeans> getCartJSON(HttpSession session){
		String sid = (String)session.getAttribute("sid");
		MemberBeans member = memberService.getMemberById(sid);
		List<CartBeans> cartList = null;
		ArrayList<ProductBeans> productList = new ArrayList<ProductBeans>();
		
		try{
			cartList = cartService.getCartListByMemberNo(member.getMember_no());
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		for(CartBeans cart : cartList){
			try{ 
				ProductBeans temp = productService.getProductByNo(cart.getCart_product());
				temp.setProduct_count(cart.getCart_count());
				System.out.println("temp : " + temp);
				productList.add(temp);
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		
		return productList;
	}
}
